function UpdateSubscriptions()
{
	var replies = Options.Subscriptions.RepliesToPosts;
	for(var i = 0; i < replies.length; ++i)
	{
		var cur = replies[i];
		XHR.SendRequest(cur.url + "&page=e#a", (function(xhr)
		{
			var cur = xhr._tag;
			var lastPost = (xhr.responseText || "").match(
				/<a\s*name=a><\/a>\s*<a\s*name=(.*?)><\/a>\s*<div\s*class="t5"\s*>[\s\S]*?<\/th>\s*<\/tr>\s*<\/table>\s*<\/div>/i);
			if(lastPost && lastPost[1] && cur.lastPost != lastPost[1])
			{
				cur.lastPost = lastPost[1];
				ReplaceSubscriptionItem(cur, "RepliesToPosts");

				var user = lastPost[0].match(/<a href="u\.php\?action=show&uid=\d+"[^>]*>([^<>]+?)<\/a>/i);

				var notification = webkitNotifications.createNotification(
					"images/icons/qshpan_48.png", 
					"您订阅的帖子有新回复了！", 
					cur.title +	( (user && user[1]) ? 
					("：由" + user[1] + "回复") : "") );
				notification.onclick = (function()
				{
					CreateTab(cur.url + "&page=e#a");
					notification.cancel();
				});
				notification.show();
			}
		}), null, {tag:cur});
	}
}

function ReplaceSubscriptionItem(item, subscription_name)
{
	var old = Options.Subscriptions._getProperty(subscription_name);
	for(var i = 0; i < old.length; ++i)
		if(old[i].url == item.url) //Assuming that URLs can identify an item
		{
			old[i] = item;
			break;
		}
	Options.Subscriptions._setProperty(subscription_name, old);
}

function UpdateLastPost(url, post)
{
	var old = Options.Subscriptions._getProperty("RepliesToPosts");
	for(var i = 0; i < old.length; ++i)
		if(old[i].url == url) //Assuming that URLs can identify an item
		{
			old[i].lastPost = post;
			break;
		}
	Options.Subscriptions._setProperty("RepliesToPosts", old);
}

function onSubscriptionMessage(message, sender, sendResponse)
{
	if(message.url && message.lastPost && message.type == "replies")
	{
		console.log(message);
		UpdateLastPost(message.url, message.lastPost);
	}
	sendResponse();
}

if(Options.Subscriptions.RepliesToPosts.length)
	Timer.Add("UpdateSubscriptions", UpdateSubscriptions, 5, true, true);

